import { _decorator, AnimationClip, Component, Node, Animation, Sprite, SpriteFrame } from 'cc'
import { ANIMATION_GRAPH_TYPE_ENUM, ENTITY_STATE_ENUM } from '../enums'
import { State } from '../base/State'
import { PLAYER_ANIMATION_PATH } from '../utils/constants'
import { SubStateMachine } from './SubStateMachine'
const { ccclass, property } = _decorator
/** 状态机基类 */
export type PARAMS_VALUE_TYPE = number | boolean

export interface IParamsValue {
  type: ANIMATION_GRAPH_TYPE_ENUM
  value: PARAMS_VALUE_TYPE
}
@ccclass('StateMachine')
export abstract class StateMachine extends Component {
  // 当前状态
  private _currentState: State | SubStateMachine = null
  public get currentState(): State | SubStateMachine {
    return this._currentState
  }
  public set currentState(value: State | SubStateMachine) {
    this._currentState = value
    this.currentState.run() // 播放动画
  }
  // 转变动画状态的参数集合 从a动画到b动画所需触发的条件参数
  params: Map<string, IParamsValue> = new Map()
  // 存储状态机集合
  stateMachines: Map<string, State | SubStateMachine> = new Map()

  animationComponent: Animation = null
  // 用来存储异步的操作
  watingState: Array<Promise<SpriteFrame[]>> = []

  getParams(name: string) {
    if (this.params.has(name)) {
      return this.params.get(name).value
    }
  }

  setParams(name: string, value: PARAMS_VALUE_TYPE) {
    if (this.params.has(name)) {
      this.params.get(name).value = value
      this.run()
      this.resetTrigger()
    }
  }

  abstract init()

  /** 运行状态机 切换当前状态 */
  abstract run()

  /** 将触发器置为false */
  resetTrigger() {
    for (const [_, value] of this.params) {
      if (value.type === ANIMATION_GRAPH_TYPE_ENUM.TRIGGER) {
        value.value = false
      }
    }
  }
}
